<template>
  <div class="berthAssociation-page">
    <breadcrumb />
    <div class="search-container">
      <Search @search="getSearchParams" />
    </div>
    <div class="table-container">
      <div class="table-component">
        <div class="submit-btns">
          <div class="row submit-btns-left">
            <img class="icon-tips" :src="iconTips" alt="" />
            <div>仅当设备处于使用中，可进行泊位关联</div>
          </div>
          <div class="submit-btns-right">
            <el-button type="primary" class="submit-btn-status" @click="statusData">
              <img class="icon-img" :src="iconStatus" alt="" />
              批量清除关联</el-button
            >
            <el-button type="primary" class="submit-btn-import" @click="importData">
              <img class="icon-img" :src="iconImport" alt="" />导入</el-button
            >
            <el-button type="primary" class="submit-btn-export" @click="exportData">
              <img class="icon-img" :src="iconExport" alt="" />导出</el-button
            >
          </div>
        </div>
        <Table :tableData="table.data" :loading="table.loading" @table="getTableParams" />

        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="pagination.pageSizes"
            layout="total,sizes, prev, pager, next, jumper"
            :total="table.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <el-dialog
          v-model="dialogVisible"
          :title="title"
          destroy-on-close
          :before-close="handleClose"
          :close-on-click-modal="false"
          :width="componentTag === associatedBerthComponent ? '520px' : '800px'"
        >
          <component
            :is="componentTag"
            @operationDone="operationDone"
            :operationId="operationId"
          >
          </component>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup>
import breadcrumb from "@/components/breadcrumb/index.vue";
import Search from "./components/search.vue";
import Table from "./components/table.vue";
import iconTips from "@/assets/image/tips.png";
import iconStatus from "@/assets/image/btn/icon-status.png";
import iconImport from "@/assets/image/btn/icon-import.png";
import iconExport from "@/assets/image/btn/icon-export.png";
import associatedBerthComponent from "./components/associatedBerthComponent.vue";
import importComponent from "./components/importComponent.vue";
import { reactive, ref, shallowRef } from "vue";
import {
  getberthAssociationList,
  getRemoveBerthAssociation,
  getExportBerthAssociation,
} from "./request.js";
import { ElMessageBox } from "element-plus";

// 搜索
const searchModel = ref({
  keyword: "",
  sensingMode: "",
  regionId: "",
  sectionId: "",
  relatedFlag: "",
  rangeDate: [],
  startTime: "",
  endTime: "",
});
const getSearchParams = (value) => {
  // searchParams.value = value;
  console.log("value ===>", value);

  searchModel.value = value;
  getData();
};

// 弹窗
const title = ref("");
const dialogVisible = ref(false);
const componentTag = shallowRef("");
const operationId = ref("");
const operationDone = (r) => {
  dialogVisible.value = false;
  operationId.value = "";
  if (!r) {
    getData();
  }
};

const handleClose = () => {
  dialogVisible.value = false;
};

// 导入
const importData = () => {
  title.value = "导入设备关联泊位信息";
  componentTag.value = importComponent;
  dialogVisible.value = true;
};

// 导出按钮
const exportData = () => {
  ElMessageBox.confirm(`您确认要导出数据？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await getExportBerthAssociation({
      keyword: searchModel.value.keyword,
      sensingMode: searchModel.value.sensingMode,
      regionId: searchModel.value.regionId,
      sectionId: searchModel.value.sectionId,
      relatedFlag: searchModel.value.relatedFlag,
      startTime: searchModel.value.startTime,
      endTime: searchModel.value.endTime,
    })
      .then((res) => {
        const fileName = extractFileNameFromHeaders(res.headers);
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement("a");
        link.href = url;
        link.download = fileName;
        link.click();
      })
      .catch((err) => {
        console.log("err ===>", err);
      });
  });
};

function extractFileNameFromHeaders(headers) {
  const contentDisposition = headers.get("content-disposition") || "";

  const matches = contentDisposition.match(/filename\*=\s*utf-8''([^;]+)/);

  if (matches != null && matches[1]) {
    return decodeURIComponent(matches[1].replace('"', ""));
  }
  return "unknown-file.pdf"; // 默认文件名
}

const bingModeNameList = ref([]);
const bingCodeList = ref([]);
const bingTotal = ref("");

// 批量清除关联
const statusData = () => {
  if (bingModeNameList.value.length === 0) {
    ElMessage.error("请选择设备信息");
    return;
  }
  console.log("bingModeNameList ===>", bingModeNameList.value);

  if (bingModeNameList.value.length > 1) {
    bingTotal.value = `...等${bingModeNameList.value.length}条`;
  } else {
    bingTotal.value = "";
  }

  ElMessageBox.confirm(
    `您确认要清除${bingModeNameList.value[0]} [${bingCodeList.value[0]}] ${bingTotal.value}设备关联泊位信息？`,
    "温馨提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    await getRemoveBerthAssociation(bingCodeList.value).then((res) => {
      if (res.data.code === 0) {
        getData();
        ElMessage({
          type: "success",
          message: `已删除${bingModeNameList.value.length}条设备泊位关联信息`,
        });
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  });
};

// table操作
const getTableParams = (value) => {
  console.log("value ===>", value);
  if (value.operation === 1) {
    title.value = "配置关联泊位";
    componentTag.value = associatedBerthComponent;
  } else if (value.operation === 2) {
    bingModeNameList.value = value.bingModeNameList;
    bingCodeList.value = value.bingCodeList;
    return;
  }
  operationId.value = value;
  dialogVisible.value = true;
};

// 表格
const table = reactive({
  data: [],
  total: 0,
  loading: true,
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 30, 50],
});

const handleCurrentChange = (value) => {
  pagination.currentPage = value;
  getData();
};

const handleSizeChange = (value) => {
  pagination.pageSize = value;
  getData();
};

const getData = () => {
  getberthAssociationList({
    keyword: searchModel.value.keyword,
    sensingMode: searchModel.value.sensingMode,
    regionId: searchModel.value.regionId,
    sectionId: searchModel.value.sectionId,
    relatedFlag: searchModel.value.relatedFlag,
    startTime: searchModel.value.startTime,
    endTime: searchModel.value.endTime,
    pageNo: pagination.currentPage,
    pageSize: pagination.pageSize,
  }).then((res) => {
    if (res.data.code === 0) {
      table.data = res.data.result.items.map((item) => {
        if (item.sensingMode === "1") {
          item.sensingModeName = "地磁传感器";
        } else if (item.sensingMode === "2") {
          item.sensingModeName = "视频桩";
        } else if (item.sensingMode === "3") {
          item.sensingModeName = "高位视频(双目)";
        } else {
          item.sensingModeName = "高位视频(球机)";
        }
        return item;
      });
      console.log("table.data ===>", table.data);

      table.total = parseInt(res.data.result.total);
      table.loading = false;
    }
  });
};

getData();
</script>

<style lang="less" scoped>
.berthAssociation-page {
  .search-container {
    margin-top: 16px;
    min-height: 100%;
    padding: 24px 24px 8px 24px;
    background: #fff;
    border-radius: 6px;
  }
  .table-container {
    margin-top: 16px;
    min-height: 100%;
    padding: 24px;
    background: #fff;
    border-radius: 6px;
    .table-component {
      .submit-btns {
        display: flex;
        justify-content: space-between;
        margin-bottom: 24px;
      }
      .submit-btns-left {
        font-weight: 400;
        font-size: 14px;
        color: #2986ff;
        .icon-tips {
          width: 20px;
          height: 20px;
          margin-right: 6px;
        }
      }
      .submit-btns-right {
        display: flex;
      }

      .submit-btn-status {
        background: #ff9623;
        border: 1px solid #ff9623;
        border-radius: 2px;
        margin-left: 87px;
        padding: 5px 16px;
      }
      .submit-btn-import {
        background: #00d1ff;
        border: 1px solid #00d1ff;
        border-radius: 2px;
        margin-left: 12px;
        padding: 5px 16px;
      }
      .submit-btn-export {
        background: #35c362;
        border: 1px solid #35c362;
        border-radius: 2px;
        margin-left: 12px;
        padding: 5px 16px;
      }
      .icon-img {
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }
    }
    .pagination {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
  .row {
    display: flex;
    align-items: center;
  }
}
</style>
